use std::sync::Arc;

use axum::{
    extract::{Path, State},
    routing::get,
    Json, Router,
};
use chrono::Local;

use crate::{form, model, utils, AffResp, AppState, Error, IdResp, JsonResp, Resp, Result};

pub async fn get_id(State(state): State<Arc<AppState>>) -> Result<JsonResp<IdResp>> {
    let id = utils::new_id();
    let pool = utils::get_pool(&state);
    let m = model::Note {
        id,
        dateline: Local::now(),
        ..Default::default()
    };
    let id = m.insert(&*pool).await.unwrap();
    Ok(Json(Resp::ok(IdResp { id })))
}

pub async fn update(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
    Json(frm): Json<form::Update>,
) -> Result<JsonResp<AffResp>> {
    let pool = utils::get_pool(&state);
    let m: model::Note = model::Note { id, ..frm.into() };
    let rows = m.update(&*pool).await.map_err(Error::from)?;
    Ok(Json(Resp::ok(AffResp { rows })))
}
pub async fn find(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<JsonResp<model::Note>> {
    let f = model::NoteFindFilter {
        by: model::NoteFindBy::Id(id),
    };
    let pool = utils::get_pool(&state);
    let m = model::Note::find(&*pool, &f).await.map_err(Error::from)?;
    let m = match m {
        Some(v) => v,
        None => return Err(Error::not_found("不存在的记录")),
    };
    Ok(Json(Resp::ok(m)))
}

pub fn init_router(state: Arc<AppState>) -> Router {
    Router::new()
        .route("/id", get(get_id))
        .route("/:id", get(find).post(update))
        .with_state(state)
}
